package com.aishua.fire.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.aishua.fire.common.exp.ValidateException;
import com.alibaba.fastjson.JSON;

@Component
public class ValidateUtil {
	
	public void respErrorMsg(BindingResult result) throws ValidateException {
		if(result.hasErrors()) {
			List<FieldError> fieldErrors = result.getFieldErrors();
			Map<String, String> map = new HashMap<String,String>();
			for(int i =0;i<fieldErrors.size();i++) {
				FieldError fieldError = fieldErrors.get(i);
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			String jsonStr = JSON.toJSONString(map);
			throw new ValidateException(jsonStr);
		}
	}
	
	public void addCustomerError(String fieldName,String fieldMessage) throws ValidateException {
		Map<String, String> map = new HashMap<String,String>();
		map.put(fieldName,fieldMessage);
		String jsonStr = JSON.toJSONString(map);
		throw new ValidateException(jsonStr);
	}
	
	public void addCustomerError(String fieldMessage) throws ValidateException {
		String jsonStr = JSON.toJSONString(fieldMessage);
		throw new ValidateException(jsonStr);
	}
}
